package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.domain.SysUserRole;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 *
 * @author Gzl
 * @date 2025-08-06
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private IAlertDataService alertDataService;
    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    @Override
    public void alertFilter() {
        //查询所有的报警规则
        long count = count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        if (count <= 0) {
            return;
        }
        //查询所有设备上报的数据
        List deviceDataList = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollectionUtil.isEmpty(deviceDataList)) {
            return;
        }
        ArrayList<DeviceData> deviceDatas = new ArrayList<>();
        //解析上报的数据
        deviceDataList.forEach(deviceData -> {
            List<DeviceData> list = JSONUtil.toList(deviceData.toString(), DeviceData.class);
            deviceDatas.addAll(list);
        });

        //处理报警数据
        deviceDatas.forEach(deviceData -> {
            alertFilter(deviceData);
        });
    }

    private void alertFilter(DeviceData deviceData) {
        //查询所有的设备上报数据

        //查询所有的报警规则
        List<AlertRule> list = this.list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
        );
        if (CollectionUtil.isEmpty(list)) {
            return;
        }

        //遍历每一条规则
        list.forEach(alertRule -> {
            deviceDataAlarmHandle(alertRule, deviceData);
        });
    }

    //效验报警规则
    private void deviceDataAlarmHandle(AlertRule alertRule, DeviceData deviceData) {
        //判断是否在生效时间内
        //获取警报生效时间段
        String[] time = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(time[0]);
        LocalTime endTime = LocalTime.parse(time[1]);
        //获取上报时间
        LocalTime alertTime = deviceData.getAlarmTime().toLocalTime();
        if (alertTime.isBefore(startTime) || alertTime.isAfter(endTime)) {
            return;
        }
        //检验数据是否达到阈值
        String iotId = deviceData.getIotId();
        //设置报警数量的key
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        //获取阈值
        Long value = alertRule.getValue();
        //获取数据
        Double dataValue = Double.valueOf(deviceData.getDataValue());
        //使用工具类NumberUtil 判断数据是否达到阈值
        int compare = NumberUtil.compare(dataValue, value);
        if ((compare >= 0 && alertRule.getOperator().equals(">=")) || (compare < 0 && alertRule.getOperator().equals("<"))) {

            log.info("当前上报的数据符合规则异常");
        } else {
            log.info("当前上报的数据不符合规则异常");
            //TODO 删除redis报警数
            //正常数据，并删除redis报警数，然后直接返回
            redisTemplate.delete(aggCountKey);
            return;
        }

        //判断沉默周期

        String silentKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        //Redis中查询沉默周期
        String silentData = (String) redisTemplate.opsForValue().get(silentKey);
        if (StringUtils.isNotEmpty(silentData)) {
            return;
        }
        //判断持续周期
        //设置持续周期的key
        String durationKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        //Redis中查询已经报警的次数
        String aggCountData = (String) redisTemplate.opsForValue().get(durationKey);
        int count = StringUtils.isEmpty(aggCountData) ? 1 : Integer.parseInt(aggCountData) + 1;
        //报警次数是否等于持续周期
        if (ObjectUtil.notEqual(count, alertRule.getDuration())) {
            redisTemplate.opsForValue().set(aggCountKey, String.valueOf(count));
            return;
        }

        //校验全部通过，则进行报警
        //删除redis中的报警次数
        redisTemplate.delete(aggCountKey);
        //添加redis的沉默周期
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //发送报警数据， 但需要先找到对应的人
        List<Long> userIds = new ArrayList<>();
        //判断是老人数据异常还是设备数据异常
        //老人数据异常
        if (alertRule.getAlertDataType().equals(0)) {
            //判断是随身设备还是固定设备
            if (deviceData.getLocationType().equals(0)) {
                //为0 时表示是随身设备 通过老人id查找到对应的护理员列表
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            } else if (deviceData.getLocationType().equals(1) && deviceData.getPhysicalLocationType().equals(2)) {
                //为1 时表示是固定设备 通过床位id找到老人，通过老人id找到对应的护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        } else {
            //设备数据异常
          userIds = userRoleMapper.selectUserIdByRoleName("维修工");
        }
        //不管是 老人还是设备，都给超级管理员发报警
        List<Long> managerIds = userRoleMapper.selectUserIdByRoleName("超级管理员");
        userIds.addAll(managerIds);
        //去重
        userIds = CollUtil.distinct(userIds);

        //批量保存数据
        insertAlertData(userIds,alertRule,deviceData);

    }

    /**
     * 保存报警数据
     * @param allUserIds 需要通知的用户id
     * @param alertRule 报警规则
     * @param deviceData 设备数据
     */
    private void insertAlertData(Collection<Long> allUserIds, AlertRule alertRule, DeviceData deviceData) {
        //对象拷贝
        AlertData alertData = new AlertData();
        BeanUtil.copyProperties(deviceData,alertData);
        alertData.setAlertRuleId(alertRule.getId());

        // 心率<60,持续3个周期就报警
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);
        alertData.setType(alertRule.getAlertDataType());
        // 遍历allUserIds
        List<AlertData> list = allUserIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            return dbAlertData;
        }).collect(Collectors.toList());

        // 批量保存
        alertDataService.saveBatch(list);
    }
}
